package com.onlinesshop.mall.controller;

import com.onlinesshop.mall.pojo.User;
import com.onlinesshop.mall.service.UserService;
import com.onlinesshop.mall.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
   private UserService userService;


    @RequestMapping(value="/addUser")
    public String addUser(User user, HttpServletRequest request, HttpServletResponse response){
        //生成用户注册时间
        String user_create_time= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        user.setCreate_time(user_create_time);
        //获取用户密码
        String password = request.getParameter("password");
        //将用户密码加密
        String md5 = MD5.getMD5(password);
        user.setPassword(md5);
        int i = userService.addUser(user);
        if(i==1){
            //注册成功将用户保存在session中
            request.getSession().setAttribute("user",user);
            return "index";
        }else{
            return "toRegister";
        }
    }

    /**
     * 判断用户是否已经存在
     * @param phoneNum
     * @return
     */
    @RequestMapping("/judgePhone")
    @ResponseBody
    public String judgePhone(@RequestParam(name = "phoneNum")String phoneNum){
        int userByPhone = userService.findUserByPhone(phoneNum);
        if (userByPhone>=1){
            return phoneNum+"";
        }
        return "";
    }

    /**
     * 用户登录
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/userLogin")
    public String userLogin(User user, HttpServletRequest request,HttpServletResponse response){
        //获取用户密码
        String password = request.getParameter("password");
        String md5 = MD5.getMD5(password);
        user.setPassword(md5);
        User userByPhoneAndPwd = userService.findUserByPhoneAndPwd(user);
        System.out.println(userByPhoneAndPwd);
        if(userByPhoneAndPwd != null){
            //将用户数据保存到session中
            request.getSession().setAttribute("user",userByPhoneAndPwd);
            return "redirect:/index";
        }else{
            return "redirect:/toRegister";
        }
    }

}
